<?php

header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Content-type: application/json; charset=utf-8');

require_once 'facebook/facebook.php';
require_once 'database.php';

$facebook = new Facebook(array(
  'appId'  => '202355239779232',
  'secret' => 'aef66e0360c9aefe692b7fe054f9c80a',
));

$user = $facebook->getUser();

if ($user) {
	try {
		$user_profile = $facebook->api('/me');
	} catch (FacebookApiException $e) {
		error_log($e);
		$user = null;
	}
}

if (!$user) {
	die();
}

if (!isset($_GET['lat']) || strlen(trim($_GET['lat'])) == 0) {
	die();
}

if (!isset($_GET['long']) || strlen(trim($_GET['long'])) == 0) {
	die();
}

$fbid = $_GET['fbid'];
$lat = floatval($_GET['lat']);
$long = floatval($_GET['long']);

if ($lat < 37.0 || $lat > 38.0) {
	die();
}

if ($long < -123.0 || $long > -122.0) {
	die();
}

$db = CE_Database::getInstance();
$result = new stdClass();

$sql = 'INSERT INTO disrupt (facebook_id, name, created_datetime, updated_datetime, latitude, longitude) ';
$sql .= ' VALUES (';
$sql .= ' \'' . $db->escape($user_profile['id']) . '\', ';
$sql .= ' \'' . $db->escape($user_profile['name']) . '\', ';
$sql .= ' NOW(), ';
$sql .= ' NOW(), ';
$sql .= floatval($lat) . ',';
$sql .= floatval($long) . ') ';
$sql .= ' ON DUPLICATE KEY UPDATE ';
$sql .= ' updated_datetime=NOW(), ';
$sql .= ' latitude=' . floatval($lat) . ', ';
$sql .= ' longitude=' . floatval($long);
$db->query($sql);

$sql = 'SELECT facebook_id, latitude, longitude ';
$sql .= ' FROM disrupt ';
$result->players = $db->getObjectArray($sql);

$sql = 'SELECT quest_state ';
$sql .= ' FROM disrupt ';
$sql .= ' WHERE facebook_id=\'' . $db->escape($user_profile['id']) . '\' ';
$quest_state = $db->getValue($sql);

$quests = array();

/*
$quests[] = createQuest(1, 37.7712200, -122.4045860, 'Quest complete! Recieved 100 Dubloons. Prove your worth, approach the King.  Walk to the blue patch!');
$quests[] = createQuest(2, 37.7716570, -122.4039500, 'Quest complete! You are now in the King\'s trusted circle, feasting in the banquet hall. Walk to the blue patch to sup.');
$quests[] = createQuest(3, 37.7718890, -122.4037870, 'Quest complete! Post banquet food coma.  Get rest at the blue patch.');
*/

$quests[] = createQuest(1, 37.7718890, -122.4037870, 'Quest complete! Recieved 100 Dubloons. Prove your worth, approach the King.  Walk to the blue patch!');
$quests[] = createQuest(2, 37.7722380, -122.4035610, 'Quest complete! You are now in the King\'s trusted circle, feasting in the banquet hall. Walk to the blue patch to sup.');
$quests[] = createQuest(3, 37.7721870, -122.4039110, 'Quest complete! Post banquet food coma.  Get rest at the blue patch.');
$quests[] = createQuest(4, 37.7716570, -122.4039500, 'Quest complete! After rest you must learn. Tome of Histories, grab it.');
$quests[] = createQuest(5, 37.7712200, -122.4045860, 'Quest complete! Rested and learned, meet your master and claim your reward.');


if ($quest_state >= 0 && $quest_state < count($quests)) {
	$quest = $quests[$quest_state];
	$p1 = convertPoint($lat, $long);
	$p2 = convertPoint($quest->latitude, $quest->longitude);
	$dist = distance($p1, $p2);
	
	if ($dist < 48.0) {
		$next = ($quest_state + 1) % (count($quests));
		$sql = 'UPDATE disrupt SET quest_state=' . intval($next) . ', score=score+1 WHERE facebook_id=\'' . $db->escape($user_profile['id']) . '\' ';
		$db->query($sql);
		$result->message = $quest->message;
	} else {
		$result->quest = $quest;
	}
}

$array = array();
$array[] = $result;
echo json_encode($array);

function convertPoint($latitude, $longitude) {
	// Step 1:  Convert to radians
	$latitude = floatval($latitude) / 360.0 * (2.0 * M_PI);
	$longitude = floatval($longitude) / 360.0 * (2.0 * M_PI);
	
	// Step 2:  Convert to Mercator
	$x2 = $longitude;
	$y2 = log((sin($latitude) + 1.0) / cos($latitude));
	
	// Step 3:  Translate/scale into our (rough) pixel ranges
	$x3 = 20000000.0 * ($x2 + 2.13638);
	$y3 = 20000000.0 * ($y2 - 0.71293);

	// Step 4:  Rotate
	// x' = x cos f - y sin f
	// y' = y cos f + x sin f
	$rot = 48.0 / 360.0 * 2.0 * M_PI;
	$x4 = $x3 * cos($rot) - $y3 * sin($rot);
	$y4 = $y3 * cos($rot) + $x3 * sin($rot);
	
	// Step 5:  Flip the y-axis
	$x5 = 60.0 + 1.5 * $x4;
	$y5 = 1366.0 - 1.5 * $y4;
	
	$point = new stdClass();
	$point->x = $x5;
	$point->y = $y5;
	return $point;
}

function distance($p1, $p2) {
	$dx = $p1->x - $p2->x;
	$dy = $p1->y - $p2->y;
	return sqrt($dx * $dx + $dy * $dy);
}

function createQuest($id, $lat, $lon, $msg) {
	$quest = new stdClass();
	$quest->id = $id;
	$quest->latitude = $lat;
	$quest->longitude = $lon;
	$quest->message = $msg;
	return $quest;
}

?>